<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\Business;
use App\Model\Device;
use App\Model\DistributorDevice;
use App\Model\Order;
use App\Services\SmsService;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;
use App\Services\AdapayService;

class DistributorsController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Admin $admin;
    #[Inject]
    protected Distributors $distributors;
    #[inject]
    protected AdapayService $adapayService;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**经销商列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $data['info'] = $this->admin->getInfo($request);
        $page = $request->inputs(['page','limit','keyword','parent_id','is_active','draw_active']);
        $data['list'] = $this->distributors->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
                $query->orWhere('phone', 'like', '%'.$page['keyword'].'%');
            }
            if($page['is_active'] != ''){
                $query->where('is_active', $page['is_active']);
            }
            if($page['draw_active'] != ''){
                $query->where('draw_active', $page['draw_active']);
            }
            if($page['parent_id']){
                $page['parent_id'] = json_decode($page['parent_id']);
                $query->where('parent_id', end($page['parent_id']));
            }
        })->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get(['id','avatar','name', 'owner_name', 'phone','remark',
                'rate', 'area', 'address', 'lat', 'lng', 'introduction', 'is_active',
                'settlement_type','parent_id','level','balance','service_image','draw_active',
                'draw_space','created_at','customer_service_phone'])->toArray();
        $data['total']= $this->distributors->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
                $query->orWhere('phone', 'like', '%'.$page['keyword'].'%');
            }
            if($page['is_active'] != ''){
                $query->where('is_active', $page['is_active']);
            }
            if($page['draw_active'] != ''){
                $query->where('draw_active', $page['draw_active']);
            }
            if($page['parent_id']){
                $page['parent_id'] = json_decode($page['parent_id']);
                $query->where('parent_id', end($page['parent_id']));
            }
        })->count();
        foreach($data['list'] as $k => &$v){
            if($v['level'] == Distributors::LEVEL_1){
                $v['device_count'] = Device::where('distributor_id',$v['id'])
                    ->where('child_distributor_id',0)
                    ->count();
            }else{
                $v['device_count'] = Device::where('child_distributor_id',$v['id'])
                    ->count();
            }

            $v['distributor_profit'] = DistributorDevice::where('distributor_id',$v['id'])
                ->sum('profit');
//            $v['order_count']  =Order::where('distributor_id',$v['id'])
//                ->where('status','<>',Order::STATUS_UNPAID)
//                ->count();
//            $v['draw_count']  =Order::where('distributor_id',$v['id'])
//                ->where('status','<>',Order::STATUS_UNPAID)
//                ->where('is_draw',1)
//                ->count();
        }
        return $this->success($data);
    }

    /**获取联级菜单经销商
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function all(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $list = $this->distributors->where('level',  Distributors::LEVEL_1)->orderBy('id', 'desc')
            ->get(['id','name','level'])->toArray();
        $type = $request->input('type');
        if($list){
            if($type){
                foreach($list as $k => $v){
                    $list[$k]['children'] = $this->distributors
                        ->where('level',  Distributors::LEVEL_2)
                        ->where('parent_id',$v['id'])
                        ->orderBy('id', 'desc')
                        ->get(['id','name','level'])
                        ->toArray();
                }
            }
        }
        return $this->success($list);
    }

    /**修改状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request):ResponseInterface
    {
        $status = $request->input('status',0,'int');
        $id = $request->input('id',0,'int');
        if (!$id) {
           return $this->error(code:1001,msg:'缺失参数id');
        }
        $this->distributors->where('id',$id)->update(['is_active'=>$status]);
        return $this->success(msg:'修改成功');
    }

    /**创建经销商
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $data = $request->post();
        if(!$data['parent_id']){
            $data['parent_id'] = 0;
            $data['level'] = Distributors::LEVEL_1;
        }

        if(isset($data['password']) && $data['password']){
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        if(array_key_exists('device_count',$data)){
            unset($data['device_count']);
        }
        if(array_key_exists('distributor_profit',$data)){
            unset($data['distributor_profit']);
        }
        if(array_key_exists('order_count',$data)){
            unset($data['order_count']);
        }
        if(array_key_exists('draw_count',$data)){
            unset($data['draw_count']);
        }

        if($data['rate'] > 100){
            return $this->error(code:1001,msg:'经销商分润不可超过100');
        }
        if (array_key_exists('id',$data) && $data['id'] > 0) {
            $id = $data['id'];
            if(array_key_exists('updated_at', $data)){
                unset($data['updated_at']);
            }
            unset($data['id']);
            $this->distributors->where('id', $id)->update($data);
        } else {
            if($data['parent_id']){
                $data['parent_id']  = end($data['parent_id']);
            }
            $parentLevel = $this->distributors->where('id',$data['parent_id'])->value('level');
            if($parentLevel >=  Distributors::LEVEL_MAX){
                return $this->error(code:1001,msg:'经销商最多不可超过'.Distributors::LEVEL_MAX.'级');
            }
            $data['level'] = $parentLevel+1;
            $checkPhone = $this->distributors->where('phone',$data['phone'])->count();
            if($checkPhone){
                return $this->error(code:1004,msg:'手机号已被占用');
            }
            Distributors::create($data);
        }
        return $this->success();
    }

    /**获取经销商绑卡信息
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function getBankInfo(RequestInterface $request):ResponseInterface{
        $id = $request->input('distributor_id',0);
        $distributor = $this->distributors->where('id',$id)
            ->first(['balance','frozen_balance','total_profit',
                'withdraw_account_type','withdraw_auto_type','withdraw_account_bank_card_username',
                'withdraw_account_bank_card_no','withdraw_account_bank_code',
                'withdraw_account_bank_name','cert_id','settle_account_id','settlement_type']);
        $distributor['bus_account'] = Business::where('distributor_id',$id)
            ->first();
        if(!$distributor){
            return $this->error(1001,'无经销商信息');
        }
        if($distributor['withdraw_account_bank_card_no']){
            $distributor['withdraw_account_bank_card_no'] = $this->normal->maskBankCard($distributor['withdraw_account_bank_card_no']);
        }
        if($distributor['cert_id']){
            $distributor['cert_id'] = $this->normal->maskIDNumber($distributor['cert_id']);
        }
        if($distributor['bus_account'] && $distributor['bus_account']['card_no']){
            $distributor['bus_account']['card_no'] = $this->normal->maskBankCard($distributor['bus_account']['card_no']);
        }
        return $this->success($distributor);
    }

}
